/**
* 把加载好的图片加入指定容器
*/
package com.tudou.top2.view
{
	import asset.NextButton_Up;
	import asset.SmallButton_Movie;
	import asset.Style_Background;
	
	import caurina.transitions.Equations;
	import caurina.transitions.Tweener;
	
	import com.tudou.top2.controller.LoadPicts;
	import com.tudou.top2.events.PictEvent;
	import com.tudou.top2.model.AdDataModel;
	import com.tudou.top2.model.PictsDataModel;
	import com.tudou.top2.model.SmallBox;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	import flash.net.sendToURL;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.utils.Timer;
	
	public class PlacePicts extends Sprite
	{
		//下面为广告打开的状态
		private static const OPENING:String = "Opening";
		private static const CLOSING:String = "Closing";
		private static const OPEN:String = "Open";
		private static const CLOSE:String = "Close"
		
		//
		private var loadPicts:LoadPicts;
		//广告通过点击Button是否打开过
		private var isShowed:Boolean = false;
		//nextButton的点击次数
		private var countNext:int = 0;
		//广告打开的状态
		private var adStatus:String = CLOSE;
		
		//大图是否处于移动过程
		private var isMoving:Boolean = false;
		
		//关闭广告后要移动到的目标大图
		private var afterCloseAdPictIndex:uint = 0;
		
		//广告图片
		private var adPicts:AdDataModel;
		//视频图片
		private var picts:PictsDataModel;
		//四小图的父容器
		private var smallContainer:Sprite;
		//NextButton
		private var nextButton:NextButton_Up;
		//广告与图片之间的阴影
		private var shadow:Bitmap;
		//是否有广告
		private var hasAd:Boolean = false;
		
		private var inTurnTimer:Timer;
		
		private const inTurnInterval:Number = 5400;
		
		//大图的总个数
		private var arrayLength:int;
		//大图的宽度
		private var bigWidth:uint;
		//大图的高度
		private var bigHeight:uint;
		
		private const buttonXY:Point = new Point(910, 150);
		//右边距
		private const iconRight:uint = 8;
		
		public function PlacePicts()
		{
			smallContainer = new Sprite();
			
			nextButton = new NextButton_Up();
			
			var bmpData:BitmapData = new Style_Background(3, KiliTop2.flashHeight);
			shadow = new Bitmap(bmpData);
			shadow.alpha = 1;
			shadow.x = 100;
			shadow.y = 0;
			
			inTurnTimer = new Timer(inTurnInterval);
			inTurnTimer.addEventListener(TimerEvent.TIMER, changePict);
		}
		//开始轮播
		public function startTurn():void
		{
			inTurnTimer.start();
			showTitle();
		}
		
		private function changePict(te:TimerEvent):void
		{
			moveToPict(nextIndex(picts.currentPict));
		}
		
		//把所有的视频图片加入到显示
		public function placePicts(picts:PictsDataModel, loadPicts:LoadPicts):void
		{
			this.loadPicts = loadPicts;
			this.picts = picts;
			arrayLength = picts.arrayLength;
			bigWidth = KiliTop2.flashWidth;
			bigHeight = KiliTop2.flashHeight;
			
			
			setBigPict();
			setFourSmallBoxes();
			setNextButton();
			
			dispatchEvent(new PictEvent(PictEvent.PLACE_PICT_FINISHED));
		}
		//广告图片加入到显示
		public function placeAd(adPicts:AdDataModel):void
		{
			this.adPicts = adPicts;
			hasAd = adPicts.hasAd;
			setAd();
			
			trace(PictEvent.PLACE_AD_FINISHED);
			dispatchEvent(new PictEvent(PictEvent.PLACE_AD_FINISHED));
		}		

		private function get currPictSprite():Sprite
		{
			return picts.bigPicts[picts.currentPict];
		}
		//判断是否可打开
		private function movable():Boolean
		{
			if(adStatus==OPENING)
			{
				//强制打开完成
				currPictSprite.x = -KiliTop2.adBannerWidth;
				nextButton.x = buttonXY.x - KiliTop2.adBannerWidth;
				adPicts.adIcon.alpha = 0;
				openCompleteHdlr();
				
				cloesAd();
				return false;
			}
			else if(adStatus==CLOSING)
			{
				//强制完成关闭
				currPictSprite.x = 0;
				nextButton.x = buttonXY.x;
				
				closeCompleteHdlr();
				
				return false;
			}
			return true;			
		}
		//正在移动中的左边大图
		private var leftCur:int;	
			
		//移动到指定图片		
		private function moveToPict(rightIndex:int):void
		{
			//新的目标右大图
			var nsp:Sprite = picts.bigPicts[rightIndex];
			//只有一个进度条, 未加载完成
			if(nsp.numChildren == 1)
			{
				var pe:PictEvent = new PictEvent(PictEvent.LOAD_RIGHT_NOW);
				pe.index = rightIndex;				
				loadPicts.dispatchEvent(pe);
			}
			if(!movable()) return ;
			//正在移动中
			if(isMoving)
			{
				pictReset();
			}
			trace("move...");
			clearTitle();
			leftCur = picts.currentPict;
			picts.currentPict = rightIndex;
			nsp.x = bigWidth;
			
			//移动
			var pobj:Object = {x:0, time:2.6, transition:Equations.easeOutExpo, onStart:onStartHdlr, onComplete:onCompleteHdlr, onUpdate:onUpdateHdlr};
			Tweener.addTween(nsp, pobj);
			
			function onStartHdlr():void
			{
				//让Title变成透明
				var titleSprite:Sprite = Sprite(currPictSprite.getChildByName("title"));
				if(titleSprite != null)
				{
					titleSprite.alpha = 0;			
				}
				isMoving = true;
			}
			function onUpdateHdlr():void
			{
				picts.bigPicts[leftCur].x = nsp.x - bigWidth - KiliTop2.betweenWidth;
			}
			function onCompleteHdlr():void
			{
				isMoving = false;
				trace("removeTweener\t" + Tweener.removeTweens(nsp, ["x"]));
				//轮播重新开始
				inTurnTimer.reset();
				inTurnTimer.start();
				showTitle();
			}
		}
		
		private function showTitle():void
		{
			if(currPictSprite.numChildren == 1) return ;
			trace("showTitle()");
			
			var titleSprite:Sprite = Sprite(currPictSprite.getChildByName("title"));
			if(titleSprite != null)
			{
				titleSprite.alpha = 0;
			}
			Tweener.addTween(titleSprite, {alpha:1, time:2.6, transition:Equations.easeOutExpo, onUpdate:onUpdateHdlr, onComplete:onCompleteHdlr});
			function onUpdateHdlr():void
			{
			}
			function onCompleteHdlr():void
			{
				Tweener.removeTweens(titleSprite, ["alpha"]);
			}
			
		}
		private function clearTitle():void
		{
			if(currPictSprite.numChildren == 1) return ;
			trace("clear title");
			var titleSprite:Sprite = Sprite(currPictSprite.getChildByName("title"));
			if(titleSprite != null)
			{
				Tweener.removeTweens(titleSprite, ["alpha"]);
				titleSprite.alpha = 0;
			}
		}
		
		private function getTitle(sp:Sprite):Sprite
		{
			return Sprite(sp.getChildByName("title"));
		}
		//图片加速复位
		private function pictReset():void
		{
			var titleSprite:Sprite;
			trace("resetPict...");
			var sp:Sprite = picts.bigPicts[picts.currentPict];
			trace("removeTweener\t" + Tweener.removeTweens(sp, ["x"]));
			sp.x = 0;
			
			titleSprite = getTitle(sp);
			if(titleSprite != null)
			{
				Tweener.removeTweens(titleSprite, ["alpha"]);
				titleSprite.alpha = 0;
			}
			
			picts.bigPicts[leftCur].x = -bigWidth - KiliTop2.betweenWidth;
			titleSprite = getTitle(picts.bigPicts[leftCur]);
			if(titleSprite != null)
			{
				Tweener.removeTweens(titleSprite, ["alpha"]);
				titleSprite.alpha = 0;
			}
		}
		private function movePictLeft():void
		{
			//加上Mask
			this.mask = KiliTop2.myMask;
			var curPict:Sprite = picts.bigPicts[picts.currentPict];
			//button与图片位置差
			var off:int = curPict.x - nextButton.x
			var pobj:Object = {x:-KiliTop2.adBannerWidth, time:1, onStart:onStartHdlr, onComplete:openCompleteHdlr, onUpdate:onUpdateHdlr};
			Tweener.addTween(curPict, pobj);
			function onStartHdlr():void
			{
				
				adPicts.adIcon.mouseEnabled = false;
				adPicts.adIcon.mouseChildren = false;
				//广告可见
				adPicts.adPict.visible = true;
				//显示到最上层
				addChild(shadow);
				moveShadow();
			}
			function onUpdateHdlr():void
			{
				//图标消失
				adPicts.adIcon.alpha = (KiliTop2.adBannerWidth + curPict.x) / KiliTop2.adBannerWidth;
				//Button左移
				nextButton.x = curPict.x - off;
				//阴影左移
				moveShadow();
			}
			
		}
		private	function openCompleteHdlr():void
		{
			var curPict:Sprite = picts.bigPicts[picts.currentPict];
			adStatus = OPEN;
			Tweener.removeTweens(curPict, ["x"]);
			adPicts.adIcon.y = 607;
			trace("opened!");
		}			
		private function movePictRight():void
		{
			var curPict:Sprite = picts.bigPicts[picts.currentPict];
			//button与图片位置差
			var off:int = curPict.x - nextButton.x
			var pobj:Object = {x:0, time:0.4, onStart:onStartHdlr, onComplete:closeCompleteHdlr, onUpdate:onUpdateHdlr};
			Tweener.addTween(curPict, pobj);
			function onStartHdlr():void
			{
				moveShadow();
			}
			function onUpdateHdlr():void
			{
				//Button右移
				nextButton.x = curPict.x - off;
				moveShadow();
			}
		}
		private function closeCompleteHdlr():void
		{
			this.mask = null;
			var curPict:Sprite = picts.bigPicts[picts.currentPict];
			adStatus = CLOSE;
			Tweener.removeTweens(curPict, ["x"]);
			//广告不可见
			adPicts.adPict.visible = false;
			//图标显现
			adPicts.adIcon.y = KiliTop2.flashHeight - KiliTop2.iconHeight;
			adPicts.adIcon.alpha = 1;
			//阴影
			shadow.x = -607;
			//下一张大图
			moveToPict(afterCloseAdPictIndex);
			//
			adPicts.adIcon.mouseEnabled = true;
			adPicts.adIcon.mouseChildren = true;
		}			
		private function moveShadow():void
		{
			shadow.x = currPictSprite.x + KiliTop2.flashWidth;
		}
		//判断当点击NextButton时是否显示图片
		private function judgeShowAd():Boolean
		{
			return hasAd && !isShowed && countNext>=3 && adPicts.isLoaded; 
		}
		//广告划出
		private function showAd():void
		{
			trace("ad showing...");
			if(isMoving)
			{
				pictReset();
			}
			//显示标题
			var titleSprite:Sprite = Sprite(currPictSprite.getChildByName("title"));
			if(titleSprite != null)
			{
				titleSprite.alpha = 1;
			}
			isShowed = true;
			adStatus = OPENING;
			movePictLeft();
			
		}
		//广告消失
		private function cloesAd():void
		{
			trace("ad closing...");
			adStatus = CLOSING;
			movePictRight();
		}
		//摆放NextButton
		private function setNextButton():void
		{
			nextButton.x = buttonXY.x;
			nextButton.y = buttonXY.y;
			nextButton.alpha = 1;
			nextButton.buttonMode = true;
			nextButton.useHandCursor = true;
			
			nextButton.addEventListener(MouseEvent.MOUSE_DOWN, nextButtonHandler);
			
			addChild(nextButton);
		}
		
		//摆放广告
		private function setAd():void
		{
			addChild(adPicts.adIcon);
			adPicts.adIcon.addEventListener(MouseEvent.MOUSE_OVER, function(me:MouseEvent):void
				{
					//计时器停止
					trace("mouse over!");
					inTurnTimer.stop();
					showAd();
				}
			);	
			adPicts.adPict.visible = false;
			addChildAt(adPicts.adPict, 0);
			adPicts.adPict.addEventListener(MouseEvent.CLICK, function(me:MouseEvent):void
				{
					sendAdMonitor();
				}
			);
			
		}
		//摆放大图
		private function setBigPict():void
		{
			//加入显示列表
			for(var i:int=0; i<arrayLength; i++)
			{
				var sp:Sprite = picts.bigPicts[i]
				addChild(sp);
				sp.x = bigWidth + KiliTop2.betweenWidth;
			}
			//current
			picts.bigPicts[picts.currentPict].x = 0;
				
		}
		//摆放小图
		private function setFourSmallBoxes():void
		{
			//将四个小Box放入smallContainer中,并调整box位置
			for(var i:int=0; i<4; i++)
			{
				setOneSmallBox(picts.smallBoxes[i], i);
			}
			var leftTop:DisplayObject = smallContainer.getChildAt(0);
			var rightTop:DisplayObject = smallContainer.getChildAt(1);
			var leftBottom:DisplayObject = smallContainer.getChildAt(2);
			var rightBottom:DisplayObject = smallContainer.getChildAt(3);
			
			leftTop.x = 0;
			leftTop.y = 0;
			
			leftBottom.x = 0;
			leftBottom.y = 128;

			rightTop.x = 135;
			rightTop.y = 0;

			rightBottom.x = 135;
			rightBottom.y = 128;

			addChild(smallContainer);
			smallContainer.x = 100;
			smallContainer.y = 80;
		}
		//处理一个SmallBox
		private function setOneSmallBox(small:SmallBox, index:int):void
		{
			//存放button和Title
			var buttonAndText:Sprite = new Sprite();
			smallContainer.addChild(buttonAndText);
			{
				var smb:SmallButton_Movie = new SmallButton_Movie();
				buttonAndText.addChild(smb);
				{
					smb.image.addChild(small.smallPict);
					smb.image.x = -smb.image.width/2;
					smb.image.y = -smb.image.height/2;

					smb.buttonMode = true;
					smb.useHandCursor = true;
					smb.addEventListener(MouseEvent.MOUSE_OVER, function(me:MouseEvent):void{smb.gotoAndPlay("over");});
					smb.addEventListener(MouseEvent.MOUSE_OUT, function(me:MouseEvent):void{smb.gotoAndPlay("out");});
					//Over切换到对应视频图片
					smb.addEventListener(MouseEvent.MOUSE_OVER, function(me:MouseEvent):void
						{
							if(picts.currentPict != index)
							{
								afterCloseAdPictIndex = index; 
								if(adStatus == OPEN)
								{
									cloesAd();
								}
								else
								{
									inTurnTimer.stop();
									moveToPict(index);
								}
							}
						}
					);
					//点击跳到对应视频
					smb.addEventListener(MouseEvent.CLICK, function(me:MouseEvent):void
						{
							navigateToURL(new URLRequest(picts.links[index]), "_blank");
						}
					);
				}
				var tf:TextField = new TextField();
				buttonAndText.addChild(tf);
				{

					tf.x = -135/2;
					tf.y = 109/2;

					tf.width = 135;
					trace("------------------" + tf.x, tf.y, tf.width);
					tf.selectable = false;
					tf.type = TextFieldType.DYNAMIC;
					tf.autoSize = TextFieldAutoSize.CENTER;
					tf.wordWrap = false;
					tf.multiline = true;
					
					tf.text = small.title;
					tf.textColor = small.textColor;
				}
			}
		}
		private function nextButtonHandler(me:MouseEvent):void
		{
			//广告打开或关闭的过程中，不能点击
			if(adStatus == OPENING || adStatus == CLOSING) return ;
			
			//点击加一
			countNext++;
			//计时器停止
			inTurnTimer.stop();
			
			if(judgeShowAd())
			{
				//放广告
				showAd();
			}
			else if(adStatus == OPEN)
			{
				afterCloseAdPictIndex = nextIndex(picts.currentPict);
				cloesAd();
			}
			else
			{
				moveToPict(nextIndex(picts.currentPict));
			}
		}
		
		private function nextIndex(cur:int):int
		{
			var i:int = (cur+1)%arrayLength;
			trace("current = " + cur + "\tclick next = " + i);
			return i;
		}
		
		private function sendAdMonitor():void
		{
			sendNeilson();
			
			var request:URLRequest = new URLRequest();
			var values:URLVariables = new URLVariables();
			values.juid = KiliTop2.monitor.juid;
			values.userId = KiliTop2.monitor.userId;
			values.adPositionId = KiliTop2.monitor.adPositionId;
			values.throwId = KiliTop2.monitor.throwId;
			values.ownerId = KiliTop2.monitor.ownerId;
			values.link = KiliTop2.monitor.link;
			values.isBar = 0;
			
			request.url = "http://adplay.tudou.com/adcontrol/adCPTClickServlet";
			request.data = values;
			request.method = URLRequestMethod.GET;
			
			navigateToURL(request, "_blank");
		}
		
		private function sendNeilson():void
		{
			if(KiliTop2.monitor.isNielson == '1')
			{
				var arr:Array =
					[
						'ca' + KiliTop2.monitor.adPositionId,
						'ch' + '00',
						'su01',
						'ad' + KiliTop2.monitor.ownerId,
						't3',
						'cr' + KiliTop2.monitor.throwId,
						'do01'
					];
				sendToURL(new URLRequest('http://secure-cn.imrworldwide.com/cgi-bin/m?ci=cn-vtudou&cg=0&si=' + arr.join('/')));
			}
		}
		
		public function resetBigPictPosition():void
		{
			var sp:Sprite;
			if(picts == null)
			{
				return ;
			}
			for(var i:int; i<picts.arrayLength; i++)
			{
				if(i != picts.currentPict)
				{
					sp = picts.bigPicts[i];
					sp.x= - KiliTop2.betweenWidth - KiliTop2.flashWidth; 
				}
			}
		}
		
	}
	
}


